<template>
	<div style="border: 1px solid #ccc">
		<Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
		<Editor style="height: 500px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
	</div>
</template>

<script setup>
import * as FileAPI from '@/api/file.js';
import '@wangeditor/editor/dist/css/style.css'; // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted, computed, getCurrentInstance } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';

// 内容 HTML
const props = defineProps(['modelValue']);
const emit = defineEmits(['update:modelValue']);
const valueHtml = computed({
	get() {
		return props.modelValue;
	},
	set(value) {
		emit('update:modelValue', value);
	}
});

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

const mode = ref('default'); // 或 'simple'
const toolbarConfig = {};
const editorConfig = {
	placeholder: '请输入内容...',
	MENU_CONF: {}
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
	const editor = editorRef.value;
	if (editor == null) return;
	editor.destroy();
});

const handleCreated = editor => {
	editorRef.value = editor; // 记录 editor 实例，重要！
};

const { proxy } = getCurrentInstance();
editorConfig.MENU_CONF['uploadImage'] = {
	// server: '/api/upload-img',

	timeout: 5 * 1000, // 5s

	// fieldName: 'custom-fileName',
	// meta: { token: 'xxx', a: 100 },
	// metaWithUrl: true, // join params to url
	// headers: { Accept: 'text/x-json' },

	maxFileSize: 2 * 1024 * 1024, // 2M

	base64LimitSize: 5 * 1024, // insert base64 format, if file's size less than 5kb

	// onBeforeUpload(file) {
	// 	console.log('onBeforeUpload', file);

	// 	return file; // will upload this file
	// 	// return false // prevent upload
	// },

	onSuccess(file, res) {
		console.log('onSuccess', file, res);
	},
	onFailed(file, res) {
		alert(res.message);
		console.log('onFailed', file, res);
	},
	onError(file, err, res) {
		alert(err.message);
		console.error('onError', file, err, res);
	},

	// customInsert(res, insertFn) {
	// 	console.log('customInsert', res);
	// 	const imgInfo = res.data[0] || {};
	// 	const { url, alt, href } = imgInfo;
	// 	if (!url) throw new Error(`Image url is empty`);

	// 	console.log('Your image url ', url);
	// 	insertFn(url, alt, href);
	// },

	customUpload(file, insertFn) {
		console.log('customUpload', file);		
		let formData = new FormData();
		formData.append("file", file);
		formData.append("dir", "wangeditor");
		FileAPI.uploadFile(formData).then(result => {
			console.log(result);
			const url = proxy.$fullUrl(result.data.url);
			insertFn(url, 'Uploaded Image', url);
		});
	},
	
};
</script>
